//
//  ViewController.m
//  TestCoreMotion
//
//  Created by qm on 15/3/19.
//  Copyright (c) 2015年 qm. All rights reserved.
//

#import "ViewController.h"
#import "CustomView.h"
#import <CoreMotion/CoreMotion.h>
#import "PNLineChartView.h"
#import "PNPlot.h"
#define UPDATE_INTERVAL_TIME 1
#define WAVEHEIGHT 3.0

typedef enum _MotionDirection {UNKNOWDIRECTION=0,UP,DOWN,LEFT,RIGHT,OVER,UNDER}MotionDirection;

@interface ViewController (){
    long lastUpdateTime;
    int steps;
}

@property (nonatomic , strong)CMMotionManager *motionManager;
@property (nonatomic,assign) MotionDirection motionDirection;
@property (strong, nonatomic)IBOutlet PNLineChartView *lineChartView;
@property (strong, nonatomic)IBOutlet UILabel *label;
@property (strong, nonatomic)IBOutlet UILabel *bushuLabel;

@property (nonatomic,strong)NSMutableArray* xData;
@property (nonatomic,strong)NSMutableArray* yData;
@property (nonatomic,strong)NSMutableArray* zData;
@property (nonatomic,strong)NSMutableArray* allData;

@end

@implementation ViewController
@synthesize lineChartView,xData,label,yData,zData,allData,bushuLabel;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    xData = [NSMutableArray array];
    yData = [NSMutableArray array];
    zData = [NSMutableArray array];
    allData = [NSMutableArray array];

    
    [self.view setBackgroundColor:[UIColor grayColor]];
    
    if (!_motionManager) {
        _motionManager = [[CMMotionManager alloc] init];
    }
    
    self.lineChartView.max = 6;
    self.lineChartView.min = -5;
    
    self.lineChartView.interval = (self.lineChartView.max-self.lineChartView.min)/22;
    
    NSMutableArray* yAxisValues = [@[] mutableCopy];
    for (int i=0; i<22; i++) {
        NSString* str = [NSString stringWithFormat:@"%.2f", self.lineChartView.min+self.lineChartView.interval*i];
        [yAxisValues addObject:str];
    }

    NSMutableArray* xxAxisValues = [@[] mutableCopy];
    for (int i=0; i<200; i++) {
        NSString* str = [NSString stringWithFormat:@"%d",i];
        [xxAxisValues addObject:str];
    }
    
    self.lineChartView.xAxisValues = xxAxisValues;
    self.lineChartView.yAxisValues = yAxisValues;
    self.lineChartView.axisLeftLineWidth = 39;
    
}
- (IBAction)start:(id)sender{
    [self startMotion];
    

}
- (IBAction)clear:(id)sender{

    for (UIView *v in self.lineChartView.subviews) {
        [v removeFromSuperview];
    }
    [xData removeAllObjects];
    [yData removeAllObjects];
    [zData removeAllObjects];
    [allData removeAllObjects];
    steps = 0;
    [self.bushuLabel setText:@""];
    [self.lineChartView setNeedsDisplay];

}
- (IBAction)stop:(id)sender{
    [self stopMotion];
    

    PNPlot *plotx = [[PNPlot alloc] init];
    
    plotx.plottingValues = xData;
    
    plotx.lineColor = [UIColor redColor];//x
    
    plotx.lineWidth = 0.5;
    
    [self.lineChartView addPlot:plotx];
    
    PNPlot *ploty = [[PNPlot alloc] init];
    
    ploty.plottingValues = yData;
    
    ploty.lineColor = [UIColor greenColor];//y
    
    ploty.lineWidth = 0.5;
    
    [self.lineChartView addPlot:ploty];
    
    PNPlot *plotz = [[PNPlot alloc] init];
    
    plotz.plottingValues = zData;
    
    plotz.lineColor = [UIColor blueColor];//z
    
    plotz.lineWidth = 0.5;
    
    [self.lineChartView addPlot:plotz];
    
    
    
    
    PNPlot *plotall = [[PNPlot alloc] init];
    
    plotall.plottingValues = allData;
    
    plotall.lineColor = [UIColor blackColor];//all
    
    plotall.lineWidth = 0.5;
    
    [self.lineChartView addPlot:plotall];
    
    [self.lineChartView setNeedsDisplay];
}
- (void)viewDidAppear:(BOOL)animated {
    [self becomeFirstResponder];
}

-(void)startMotion
{
    _motionDirection = UNKNOWDIRECTION;
    if(_motionManager.accelerometerAvailable)
    {
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        _motionManager.accelerometerUpdateInterval = 6.0/60.0;
        __block float x = 0.0;
        __block float y = 0.0;
        __block float z = 0.0;
        __block int i = 0;
        [_motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
            if (error)
            {
                NSLog(@"CoreMotion Error : %@",error);
                [_motionManager stopAccelerometerUpdates];
            }
            if(i == 0)
            {
                x = accelerometerData.acceleration.x;
                y = accelerometerData.acceleration.y;
                z = accelerometerData.acceleration.z;
                
            }
            
            i++;
            if(fabs(y - accelerometerData.acceleration.y) > 0.4)
            {
                
                if(y > accelerometerData.acceleration.y)
                {
                    NSLog(@"UP");
                    _motionDirection = UP;
                }
                else
                {
                    NSLog(@"Down");
                    _motionDirection = DOWN;
                }
                
                
                y = accelerometerData.acceleration.y;
                
            }
            
            if(fabs(x - accelerometerData.acceleration.x) > 0.4)
            {
                
                
                if(x > accelerometerData.acceleration.x)
                {
                    NSLog(@"LEFT");
                    _motionDirection = LEFT;
                }
                else
                {
                    NSLog(@"RIGHT");
                    _motionDirection = RIGHT;
                }
                
                
                x = accelerometerData.acceleration.x;
                
            }
            
            if(fabs(z - accelerometerData.acceleration.z) > 0.4)
            {
                
                
                if(z > accelerometerData.acceleration.z)
                {
                    NSLog(@"OVER");
                    _motionDirection = OVER;
                }
                else
                {
                    NSLog(@"UNDER");
                    _motionDirection = UNDER;
                }
                
                
                z = accelerometerData.acceleration.z;
                
            }
            
            [xData addObject:[NSNumber numberWithFloat:x]];
            [yData addObject:[NSNumber numberWithFloat:y]];
            [zData addObject:[NSNumber numberWithFloat:z]];
            [allData addObject:[NSNumber numberWithFloat:sqrt(x*x +y*y +z*z)]];
            
            NSLog(@"sqrt(x*x +y*y +z*z)=%f",sqrt(x*x +y*y +z*z));

            
            long currentTime = [[NSDate date] timeIntervalSince1970]*1000;
            
            long timeInterval = currentTime - lastUpdateTime;
            
            NSLog(@"timeInterval=%ld",timeInterval);

            if (timeInterval<UPDATE_INTERVAL_TIME) {
                return;
            }
            lastUpdateTime = currentTime;
            
            double waveH =sqrt(x*x +y*y +z*z);
            
            if (waveH>WAVEHEIGHT) {
                steps++;
                [self.bushuLabel setText:[NSString stringWithFormat:@"%d",steps/2]];
            }

            [self.label setText:[NSString stringWithFormat:@"sqrt(x*x +y*y +z*z)=%f",waveH]];

        }];
        

    }
    else
    {
        NSLog(@"The accelerometer is unavailable");
    }
}

-(void)stopMotion
{
    _motionDirection = UNKNOWDIRECTION;
    [_motionManager stopAccelerometerUpdates];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
